import axios from 'axios';
import { clientHost, serverHost, port, updateNetorkInfo } from '@/share/constants'

let api; // 延迟创建 axios 实例

// 判断当前环境
const isProduction = import.meta.env.MODE === 'production';
console.log('frontend isProduction::', isProduction);

// 用于等待服务器地址获取完成的 Promise
export const serverIpReady = new Promise(async (resolve) => {
    let networkInfo = await updateNetorkInfo();
    console.log(`URL:::http://${networkInfo.ip}:${networkInfo.serverPort}`);
    api = axios.create({
        baseURL: `http://${networkInfo.ip}:${networkInfo.serverPort}`,
    });
    resolve();
});

// 封装 API 方法，确保在 serverIpReady 之后才执行
const createApiMethod = (method) => {
    return async (...args) => {
        await serverIpReady; // 等待服务器地址获取完成
        return method(...args);
    };
};

// 获取书籍列表
export const getActivities = createApiMethod((params) => api.get('/api/activities', { params }));
export const deleteAcvitity = createApiMethod((id) => api.delete(`/api/activities/${id}`));
export const createAcvitity = createApiMethod((activity) => api.post(`/api/activities/`, activity));

export default api;